//
//  ChatLayoutModel.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/10/17.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit

let maxImageWidth: CGFloat = 200
let maxImageHeight: CGFloat = 200

class ChatLayoutModel {
    
    var height: CGFloat = 0
    var imageSize = CGSize.zero
    
    var model = ChatModel()
    
    static func layoutFrom(_ model: ChatModel) -> ChatLayoutModel {
        let layout = ChatLayoutModel()
        layout.model = model
        
        if let imageModel = model.ossList.first {
            let imageUrl = APPConfig.imagePath + imageModel.id
            if let image = SDImageCache.shared.imageFromCache(forKey: imageUrl) {
                let size = image.size
                if size.width > size.height {
                    let width = min(size.width, maxImageWidth)
                    layout.imageSize = CGSize(width: width, height: (size.height / size.width) * width)
                } else {
                    let height = min(size.height, maxImageHeight)
                    layout.imageSize = CGSize(width: (size.width / size.height) * height, height: height)
                }
            } else {
                layout.imageSize = CGSize(width: 100, height: 100)
            }
            layout.height = ceil(layout.imageSize.height) + 78
        } else {
            let attributeString = NSMutableAttributedString.init(string: model.content)
            attributeString.setTextFont(UIFont.systemFont(ofSize: 14, weight: .medium), text: model.content)
            let height = attributeString.boundingRect(with: CGSize(width: SCREEN_WIDTH - 60, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, context: nil).size.height
            layout.height = ceil(height) + 88
        }
        return layout
    }
    
}
